package cn.wolfcode.rbac.interceptor;

import cn.wolfcode.rbac.annotation.RequiredPermission;
import cn.wolfcode.rbac.model.EmployeeDO;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Lu.F
 * @version 1.0
 * @Description TODO
 * @date 2022/5/21 11:24
 */
public class CheckPermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        //获取session中的登录对象
        EmployeeDO employee = (EmployeeDO) session.getAttribute("EMPLOYEE_IN_SESSION");
        //判断登录对象是否为超级管理员
        if(employee.getAdmin()){
            return true;
        }

        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //获取当前执行的方法，强制转换为真实的类型
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //判断该方法上是否存在@RequiredPermission注解
        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        if(annotation == null){//没有@RequiredPermission，直接方法，不需要验证
            return true;
        }
        //如果有@RequiredPermission注解，获取当前登录员工的权限
        List<String> permissions = (List<String>) session.getAttribute("PERMISSION_IN_SESSION");
        //获取该注解的权限表达式
        String expression = annotation.value()[1];
        //判断该权限表达式，在员工权限集合是否存在
        if(permissions.contains(expression)){//如果存在
            return true;
        }
        //如果没有，跳转到错误提示页面
        response.sendRedirect("/no_permission");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
